package com.platform.manager.action.system;

import com.opensymphony.xwork2.ActionSupport;
import com.platform.common.annotation.logger.EnableLogger;
import com.platform.domain.TbSysFunction;
import com.platform.domain.TbSysRole;
import com.platform.domain.result.MenuFunction;
import com.platform.security.model.UserInfo;
import com.platform.service.FunctionService;
import com.platform.service.RoleService;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-8-22
 * Time: 上午10:22
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/system")
@Service("loginAction")
public class LoginAction extends ActionSupport {

    @EnableLogger
    private static Logger logger;
    @Resource
    private RoleService roleService;
    @Resource
    private FunctionService functionService;

    private List<TbSysRole> roles;

    private List<MenuFunction> menus;

    /**
     * 用户登录
     *
     * @return
     */
    @Action(value = "login", results = {@Result(name = "success", location = "/main.jsp")})
    public String login() throws Exception {
        // 获取用户信息
        UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        logger.info("登录用户名：[" + user.getTbSysUser().getName() + "]");
        logger.info("登录用户角色：[" + user.getTbSysUser().getRoleName() + "]");
        // 获取用户角色列表
        getRole(user.getTbSysUser().getUserId());
        // 获取用户当前角色对应的功能菜单列表
        getMenu(user.getTbSysUser().getRoleId());
        return SUCCESS;
    }

    /**
     * 根据用户ID查询用户角色列表
     *
     * @param userId 用户ID
     * @throws Exception
     */
    private void getRole(String userId) throws Exception {
        roles = roleService.queryRoleByUserId(userId);
    }

    /**
     * 根据角色ID查询当前角色下的菜单并进行构建
     *
     * @param roleId 角色ID
     * @throws Exception
     */
    private void getMenu(String roleId) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("functionType", "0");
        params.put("roleId", roleId);
        List<TbSysFunction> functions = functionService.queryFunctionByRoleId(params);
        // 查询结果为空则直接结束
        if (functions == null) {
            return;
        }
        //logger.info("角色ID: " + roleId + " 对就菜单项: " + functions.size());
        // 判断一级菜单项是否进行了初始化,没有则进行初始化
        if (menus == null) {
            menus = new ArrayList<MenuFunction>();
        }

        for (TbSysFunction item : functions) {
            // 判断当前菜单对象的上级菜单为空,或长度为0
            if (item.getFunSuperior() == null || item.getFunSuperior().trim().length() < 1) {
                logger.info(item.getFunSuperior());
                // 添加菜单功能对象到一级菜单列表中
                MenuFunction menuFunction = new MenuFunction();
                menuFunction.setTbSysFunction(item);
                menus.add(menuFunction);
            } else {
                // 二级菜单的构建
                buildChildMenu(item, menus);
            }
        }
        //logger.info("菜单项: " + menus.size());
    }

    /**
     * 构建二级菜单
     *
     * @param function 功能菜单
     * @param menus    菜单集合
     */
    private void buildChildMenu(TbSysFunction function, List<MenuFunction> menus) {
        for (MenuFunction item : menus) {
            if (function.getFunSuperior().trim().equals(item.getTbSysFunction().getFunctionId().trim())) {
                List<MenuFunction> childs = item.getChildMenus();
                // 判断当前菜单下的字菜单集合是否为空,为空则时行初始化
                if (childs == null) {
                    childs = new ArrayList<MenuFunction>();
                }
                // 添加菜单功能对象到二级菜单列表中
                MenuFunction menuFunction = new MenuFunction();
                menuFunction.setTbSysFunction(function);
                childs.add(menuFunction);
                item.setChildMenus(childs);
            }
        }
    }

    public List<TbSysRole> getRoles() {
        return roles;
    }

    public void setRoles(List<TbSysRole> roles) {
        this.roles = roles;
    }

    public List<MenuFunction> getMenus() {
        return menus;
    }

    public void setMenus(List<MenuFunction> menus) {
        this.menus = menus;
    }
}
